<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="format-detection" content="telephone=no"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="black"><link rel="icon" href="/blog/blog/images/icons/favicon-16x16.png?v=2.6.2" type="image/png" sizes="16x16"><link rel="icon" href="/blog/blog/images/icons/favicon-32x32.png?v=2.6.2" type="image/png" sizes="32x32"><meta name="description" content="Ajax的Get与Post方法       请注意，必须引入JQuery CDN代码如下： 1&lt;script src&#x3D;&quot;https:&#x2F;&#x2F;cdn.bootcdn.net&#x2F;ajax&#x2F;libs&#x2F;jquery&#x2F;3.6.0&#x2F;jquery.js&quot;&gt;&lt;&#x2F;script&gt;                      Get方法">
<meta property="og:type" content="article">
<meta property="og:title" content="Ajax请求PostAndGet">
<meta property="og:url" content="https://bruce-jj.gitee.io/blog/2021/04/05/Java%E6%8A%80%E5%B7%A7-Ajax%E8%AF%B7%E6%B1%82PostAndGet/index.html">
<meta property="og:site_name" content="斯人若彩虹 遇上方知有">
<meta property="og:description" content="Ajax的Get与Post方法       请注意，必须引入JQuery CDN代码如下： 1&lt;script src&#x3D;&quot;https:&#x2F;&#x2F;cdn.bootcdn.net&#x2F;ajax&#x2F;libs&#x2F;jquery&#x2F;3.6.0&#x2F;jquery.js&quot;&gt;&lt;&#x2F;script&gt;                      Get方法">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-04-05T05:51:44.000Z">
<meta property="article:modified_time" content="2021-05-06T12:26:34.000Z">
<meta property="article:author" content="何水浪">
<meta property="article:tag" content="Java编程实用小技巧">
<meta name="twitter:card" content="summary"><title>Ajax请求PostAndGet | 斯人若彩虹 遇上方知有</title><link ref="canonical" href="https://bruce-jj.gitee.io/blog/2021/04/05/Java%E6%8A%80%E5%B7%A7-Ajax%E8%AF%B7%E6%B1%82PostAndGet/"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.12.1/css/all.min.css" type="text/css"><link rel="stylesheet" href="/blog/css/index.css?v=2.6.2"><script>var Stun = window.Stun || {};
var CONFIG = {
  root: '/blog/',
  algolia: undefined,
  assistSearch: undefined,
  fontIcon: {"prompt":{"success":"fas fa-check-circle","info":"fas fa-arrow-circle-right","warning":"fas fa-exclamation-circle","error":"fas fa-times-circle"},"copyBtn":"fas fa-copy"},
  sidebar: {"offsetTop":"20px","tocMaxDepth":6},
  header: {"enable":true,"showOnPost":true,"scrollDownIcon":false},
  postWidget: {"endText":true},
  nightMode: {"enable":true},
  back2top: {"enable":true},
  codeblock: {"style":"default","highlight":"light","wordWrap":false},
  reward: false,
  fancybox: false,
  zoomImage: {"gapAside":"20px"},
  galleryWaterfall: undefined,
  lazyload: false,
  pjax: undefined,
  externalLink: {"icon":{"enable":true,"name":"fas fa-external-link-alt"}},
  shortcuts: undefined,
  prompt: {"copyButton":"复制","copySuccess":"复制成功","copyError":"复制失败"},
  sourcePath: {"js":"js","css":"css","images":"images"},
};

window.CONFIG = CONFIG;</script><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/blog/atom.xml" title="斯人若彩虹 遇上方知有" type="application/atom+xml">
</head><body><div class="container" id="container"><header class="header" id="header"><div class="header-inner"><nav class="header-nav header-nav--fixed"><div class="header-nav-inner"><div class="header-nav-menubtn"><i class="fas fa-bars"></i></div><div class="header-nav-menu"><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/blog/"><span class="header-nav-menu-item__icon"><i class="fas fa-home"></i></span><span class="header-nav-menu-item__text">首页</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/blog/archives/"><span class="header-nav-menu-item__icon"><i class="fas fa-folder-open"></i></span><span class="header-nav-menu-item__text">归档</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/blog/categories/"><span class="header-nav-menu-item__icon"><i class="fas fa-layer-group"></i></span><span class="header-nav-menu-item__text">分类</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/blog/tags/"><span class="header-nav-menu-item__icon"><i class="fas fa-tags"></i></span><span class="header-nav-menu-item__text">标签</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/blog/friends/"><span class="header-nav-menu-item__icon"><i class="fas fa-link"></i></span><span class="header-nav-menu-item__text">友链</span></a></div></div><div class="header-nav-search"><span class="header-nav-search__icon"><i class="fas fa-search"></i></span><span class="header-nav-search__text">搜索</span></div><div class="header-nav-mode"><div class="mode"><div class="mode-track"><span class="mode-track-moon"></span><span class="mode-track-sun"></span></div><div class="mode-thumb"></div></div></div></div></nav><div class="header-banner"><div class="header-banner-info"><div class="header-banner-info__title">斯人若彩虹 遇上方知有</div><div class="header-banner-info__subtitle"></div></div></div></div></header><main class="main" id="main"><div class="main-inner"><div class="content-wrap" id="content-wrap"><div class="content" id="content"><!-- Just used to judge whether it is an article page--><div id="is-post"></div><div class="post"><header class="post-header"><h1 class="post-title">Ajax请求PostAndGet</h1><div class="post-meta"><span class="post-meta-item post-meta-item--createtime"><span class="post-meta-item__icon"><i class="far fa-calendar-plus"></i></span><span class="post-meta-item__info">发表于</span><span class="post-meta-item__value">2021-04-05</span></span><span class="post-meta-item post-meta-item--updatetime"><span class="post-meta-item__icon"><i class="far fa-calendar-check"></i></span><span class="post-meta-item__info">更新于</span><span class="post-meta-item__value">2021-05-06</span></span><span class="post-meta-item post-meta-item--wordcount"><span class="post-meta-item__icon"><i class="far fa-file-word"></i></span><span class="post-meta-item__info">字数统计</span><span class="post-meta-item__value">705</span></span><span class="post-meta-item post-meta-item--readtime"><span class="post-meta-item__icon"><i class="far fa-clock"></i></span><span class="post-meta-item__info">阅读时长</span><span class="post-meta-item__value">5分</span></span></div></header><div class="post-body">
        <h1 id="Ajax的Get与Post方法"   >
          <a href="#Ajax的Get与Post方法" class="heading-link"><i class="fas fa-link"></i></a><a href="#Ajax的Get与Post方法" class="headerlink" title="Ajax的Get与Post方法"></a>Ajax的Get与Post方法</h1>
      <p><strong>请注意，必须引入JQuery</strong></p>
<p><strong>CDN代码如下：</strong></p>
<figure class="highlight html"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></div></figure>


        <h2 id="Get方法"   >
          <a href="#Get方法" class="heading-link"><i class="fas fa-link"></i></a><a href="#Get方法" class="headerlink" title="Get方法"></a>Get方法</h2>
      <p><strong>请注意GET方法一般用于从后台中获取数据，而不是提交数据</strong></p>
<p>默认是GET方法，速度很快。但是由于<strong>数据将直接以localhost:8080?data1=111&amp;data2=222</strong>的形式</p>
<p>出现在浏览器的地址栏中，</p>
<p><strong>因而Get方法一般不用于：敏感、隐私的数据传输</strong></p>
<figure class="highlight js"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> id = $(<span class="string">&quot;input[name=&#x27;editor&#x27;]&quot;</span>).val() </span><br><span class="line">$.ajax(&#123;	</span><br><span class="line">	<span class="comment">//后台的请求路径 一般在@Controller层中添加相关注解</span></span><br><span class="line">	<span class="comment">//注解一：@RequestMapping(value=&quot;/show_paper&quot;)或者指定@GetMapping(value=&quot;/show_paper&quot;)</span></span><br><span class="line">	<span class="attr">url</span>:<span class="string">&quot;show_paper&quot;</span>, </span><br><span class="line">	<span class="attr">data</span>:&#123;<span class="string">&quot;Id&quot;</span>:, id&#125;, </span><br><span class="line">	<span class="attr">type</span>:<span class="string">&quot;GET&quot;</span>,</span><br><span class="line">	<span class="comment">//注解二：由于指定返回类型为JSON数据</span></span><br><span class="line">	<span class="comment">//@ResponseBody</span></span><br><span class="line">	<span class="attr">dataType</span>:<span class="string">&quot;JSON&quot;</span>,</span><br><span class="line">	<span class="attr">success</span>:<span class="function"><span class="keyword">function</span>(<span class="params">result</span>)</span>&#123;</span><br><span class="line">		<span class="comment">//后台的回调函数中 result中可以找到 后台返回的JSON数据</span></span><br><span class="line">		<span class="built_in">console</span>.log(result);</span><br><span class="line">	&#125;,</span><br><span class="line">	<span class="attr">error</span>:<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">		alert(<span class="string">&quot;抱歉，请求失败，请重新发出请求！&quot;</span>)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></div></figure>


        <h3 id="1-在SpringBoot中，-RestController-Controller-ResponseBody"   >
          <a href="#1-在SpringBoot中，-RestController-Controller-ResponseBody" class="heading-link"><i class="fas fa-link"></i></a><a href="#1-在SpringBoot中，-RestController-Controller-ResponseBody" class="headerlink" title="1. 在SpringBoot中，@RestController=@Controller+@ResponseBody"></a>1. <strong>在SpringBoot中，@RestController=@Controller+@ResponseBody</strong></h3>
      
        <h3 id="2-使用Get方式请求时，后台SpringMVC用-RequestParam-“Id”-来获取"   >
          <a href="#2-使用Get方式请求时，后台SpringMVC用-RequestParam-“Id”-来获取" class="heading-link"><i class="fas fa-link"></i></a><a href="#2-使用Get方式请求时，后台SpringMVC用-RequestParam-“Id”-来获取" class="headerlink" title="2. 使用Get方式请求时，后台SpringMVC用@RequestParam(“Id”)来获取"></a>2. <strong>使用Get方式请求时，后台SpringMVC用@RequestParam(“Id”)来获取</strong></h3>
      
        <h2 id="Post方法"   >
          <a href="#Post方法" class="heading-link"><i class="fas fa-link"></i></a><a href="#Post方法" class="headerlink" title="Post方法"></a>Post方法</h2>
      <p>与Get方法不同的是，<strong>Post方法一般用于向服务器提交数据。而不是获取数据！</strong></p>
<p>因此，我们可以将<strong>需要隐私处理的数据以POST方式以服务器交互：比如账户密码，业务逻辑数据等等</strong></p>

        <h3 id="1-网页中没有form标签"   >
          <a href="#1-网页中没有form标签" class="heading-link"><i class="fas fa-link"></i></a><a href="#1-网页中没有form标签" class="headerlink" title="1. 网页中没有form标签"></a>1. 网页中没有form标签</h3>
      <figure class="highlight js"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> username = $(<span class="string">&quot;input[name=&#x27;username&#x27;]&quot;</span>).val() </span><br><span class="line"><span class="keyword">var</span> password = $(<span class="string">&quot;input[name=&#x27;password&#x27;]&quot;</span>).val() </span><br><span class="line">      $.ajax(&#123;</span><br><span class="line">	<span class="comment">//对应的Controller 指定登录</span></span><br><span class="line">          <span class="attr">url</span>:<span class="string">&quot;login&quot;</span>,</span><br><span class="line">	<span class="comment">//字符串拼接的方式添加参数 后台可用MVC捕捉 或创建Bean对象</span></span><br><span class="line">          <span class="attr">data</span>:&#123;<span class="string">&quot;username&quot;</span>:username , <span class="string">&quot;password&quot;</span>:password&#125;, </span><br><span class="line">          <span class="attr">type</span>:<span class="string">&quot;POST&quot;</span>,<span class="comment">//HTTP请求方式</span></span><br><span class="line">          <span class="attr">dataType</span>:<span class="string">&quot;JSON&quot;</span>,<span class="comment">//返回值的类型。</span></span><br><span class="line">          <span class="attr">success</span>:<span class="function"><span class="keyword">function</span>(<span class="params">result</span>)</span>&#123; <span class="comment">//请求事件成功的回调函数</span></span><br><span class="line">              <span class="built_in">console</span>.log(<span class="string">&quot;JSON:&quot;</span>+result);</span><br><span class="line">          &#125;,</span><br><span class="line">          <span class="attr">error</span>:<span class="function"><span class="keyword">function</span>(<span class="params">data</span>)</span>&#123;<span class="comment">//处理页面出错以后执行的函数</span></span><br><span class="line">              <span class="built_in">console</span>.log(data);</span><br><span class="line">              <span class="built_in">window</span>.location.replace(<span class="string">&quot;./index.jsp&quot;</span>);</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;);</span><br></pre></td></tr></table></div></figure>


        <h4 id="1-后台函数参数中可以使用与前端同名的变量"   >
          <a href="#1-后台函数参数中可以使用与前端同名的变量" class="heading-link"><i class="fas fa-link"></i></a><a href="#1-后台函数参数中可以使用与前端同名的变量" class="headerlink" title="1. 后台函数参数中可以使用与前端同名的变量"></a>1. 后台函数参数中可以使用与前端同名的变量</h4>
      <figure class="highlight java"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">fun</span><span class="params">(String username, String password)</span></span></span><br></pre></td></tr></table></div></figure>


        <h4 id="2-后台可以使用Bean对象-User类-其中属性与前端参数同名"   >
          <a href="#2-后台可以使用Bean对象-User类-其中属性与前端参数同名" class="heading-link"><i class="fas fa-link"></i></a><a href="#2-后台可以使用Bean对象-User类-其中属性与前端参数同名" class="headerlink" title="2. 后台可以使用Bean对象 User类 其中属性与前端参数同名"></a>2. 后台可以使用Bean对象 User类 其中属性与前端参数同名</h4>
      <p><strong>UserController.java</strong></p>
<figure class="highlight java"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">fun</span><span class="params">(User user)</span></span></span><br></pre></td></tr></table></div></figure>

<p><strong>User.java</strong></p>
<figure class="highlight java"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span></span>&#123;</span><br><span class="line">	<span class="keyword">private</span> Integer id;</span><br><span class="line">	<span class="keyword">private</span> String username;</span><br><span class="line">	pruvate String password;</span><br><span class="line">	</span><br><span class="line">	...省略GET、SET方法</span><br><span class="line">&#125;</span><br></pre></td></tr></table></div></figure>


        <h3 id="2-网页中有form标签（更便捷）"   >
          <a href="#2-网页中有form标签（更便捷）" class="heading-link"><i class="fas fa-link"></i></a><a href="#2-网页中有form标签（更便捷）" class="headerlink" title="2.网页中有form标签（更便捷）"></a>2.网页中有form标签（更便捷）</h3>
      <p><strong>关键代码</strong></p>
<figure class="highlight js"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">data:$(<span class="string">&quot;#form&quot;</span>).serialize(),</span><br></pre></td></tr></table></div></figure>

<p>解释：</p>
<ol>
<li><p>给网页中的<strong>form表单一个id=”form”</strong></p>
</li>
<li><p>在进行AJAX请求时 找到这个表单</p>
</li>
<li><p><strong>对这个表单中的数据进行序列化serialize()</strong></p>
</li>
</ol>
<p><strong>注意：后台用对象User来接收，并且前端name中的值需要与Bean对象User中的private属性一一对应</strong></p>
<figure class="highlight js"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">$.ajax(&#123;</span><br><span class="line">        <span class="attr">url</span>:<span class="string">&quot;addUser&quot;</span>,</span><br><span class="line">        <span class="attr">type</span>:<span class="string">&quot;POST&quot;</span>,</span><br><span class="line">        <span class="attr">data</span>:$(<span class="string">&quot;#form&quot;</span>).serialize(),</span><br><span class="line">        <span class="attr">success</span>:<span class="function"><span class="keyword">function</span> (<span class="params">result</span>) </span>&#123;</span><br><span class="line">            showData(result);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br></pre></td></tr></table></div></figure>
</div><footer class="post-footer"><div class="post-ending ending"><div class="ending__text">------ 本文结束，感谢您的阅读 ------</div></div><div class="post-copyright copyright"><div class="copyright-author"><span class="copyright-author__name">本文作者: </span><span class="copyright-author__value"><a href="https://bruce-jj.gitee.io/blog">何水浪</a></span></div><div class="copyright-link"><span class="copyright-link__name">本文链接: </span><span class="copyright-link__value"><a href="https://bruce-jj.gitee.io/blog/2021/04/05/Java%E6%8A%80%E5%B7%A7-Ajax%E8%AF%B7%E6%B1%82PostAndGet/">https://bruce-jj.gitee.io/blog/2021/04/05/Java%E6%8A%80%E5%B7%A7-Ajax%E8%AF%B7%E6%B1%82PostAndGet/</a></span></div><div class="copyright-notice"><span class="copyright-notice__name">版权声明: </span><span class="copyright-notice__value">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en" rel="external nofollow" target="_blank">BY-NC-SA</a> 许可协议。转载请注明出处！</span></div></div><div class="post-tags"><span class="post-tags-item"><span class="post-tags-item__icon"><i class="fas fa-tag"></i></span><a class="post-tags-item__link" href="https://bruce-jj.gitee.io/blog/tags/Java%E7%BC%96%E7%A8%8B%E5%AE%9E%E7%94%A8%E5%B0%8F%E6%8A%80%E5%B7%A7/">Java编程实用小技巧</a></span></div><nav class="post-paginator paginator"><div class="paginator-prev"><a class="paginator-prev__link" href="/blog/2021/04/09/%E4%B8%8D%E4%BC%9A%E5%90%A7%E8%80%83%E7%A0%94%E6%95%B0%E5%AD%A6/"><span class="paginator-prev__icon"><i class="fas fa-angle-left"></i></span><span class="paginator-prev__text">考研数学到底怎么样才能上一百分？我来告诉你...</span></a></div><div class="paginator-next"><a class="paginator-next__link" href="/blog/2021/04/01/VUE%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-%E5%9F%BA%E7%A1%80%E8%AF%AD%E6%B3%95%E5%8F%8A%E7%9B%B8%E5%BA%94%E5%BA%94%E7%94%A8-3/"><span class="paginator-prev__text">VUE学习笔记-3-SpringBoot+SpringJPA+Vue 开发实战</span><span class="paginator-next__icon"><i class="fas fa-angle-right"></i></span></a></div></nav></footer></div></div><div class="comments" id="comments"><div id="valine-container"></div></div></div><div class="sidebar-wrap" id="sidebar-wrap"><aside class="sidebar" id="sidebar"><div class="sidebar-nav"><span class="sidebar-nav-toc current">文章目录</span><span class="sidebar-nav-ov">站点概览</span></div><section class="sidebar-toc"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Ajax%E7%9A%84Get%E4%B8%8EPost%E6%96%B9%E6%B3%95"><span class="toc-number">1.</span> <span class="toc-text">
          Ajax的Get与Post方法</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Get%E6%96%B9%E6%B3%95"><span class="toc-number">1.1.</span> <span class="toc-text">
          Get方法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E5%9C%A8SpringBoot%E4%B8%AD%EF%BC%8C-RestController-Controller-ResponseBody"><span class="toc-number">1.1.1.</span> <span class="toc-text">
          1. 在SpringBoot中，@RestController&#x3D;@Controller+@ResponseBody</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E4%BD%BF%E7%94%A8Get%E6%96%B9%E5%BC%8F%E8%AF%B7%E6%B1%82%E6%97%B6%EF%BC%8C%E5%90%8E%E5%8F%B0SpringMVC%E7%94%A8-RequestParam-%E2%80%9CId%E2%80%9D-%E6%9D%A5%E8%8E%B7%E5%8F%96"><span class="toc-number">1.1.2.</span> <span class="toc-text">
          2. 使用Get方式请求时，后台SpringMVC用@RequestParam(“Id”)来获取</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Post%E6%96%B9%E6%B3%95"><span class="toc-number">1.2.</span> <span class="toc-text">
          Post方法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E7%BD%91%E9%A1%B5%E4%B8%AD%E6%B2%A1%E6%9C%89form%E6%A0%87%E7%AD%BE"><span class="toc-number">1.2.1.</span> <span class="toc-text">
          1. 网页中没有form标签</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-%E5%90%8E%E5%8F%B0%E5%87%BD%E6%95%B0%E5%8F%82%E6%95%B0%E4%B8%AD%E5%8F%AF%E4%BB%A5%E4%BD%BF%E7%94%A8%E4%B8%8E%E5%89%8D%E7%AB%AF%E5%90%8C%E5%90%8D%E7%9A%84%E5%8F%98%E9%87%8F"><span class="toc-number">1.2.1.1.</span> <span class="toc-text">
          1. 后台函数参数中可以使用与前端同名的变量</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-%E5%90%8E%E5%8F%B0%E5%8F%AF%E4%BB%A5%E4%BD%BF%E7%94%A8Bean%E5%AF%B9%E8%B1%A1-User%E7%B1%BB-%E5%85%B6%E4%B8%AD%E5%B1%9E%E6%80%A7%E4%B8%8E%E5%89%8D%E7%AB%AF%E5%8F%82%E6%95%B0%E5%90%8C%E5%90%8D"><span class="toc-number">1.2.1.2.</span> <span class="toc-text">
          2. 后台可以使用Bean对象 User类 其中属性与前端参数同名</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E7%BD%91%E9%A1%B5%E4%B8%AD%E6%9C%89form%E6%A0%87%E7%AD%BE%EF%BC%88%E6%9B%B4%E4%BE%BF%E6%8D%B7%EF%BC%89"><span class="toc-number">1.2.2.</span> <span class="toc-text">
          2.网页中有form标签（更便捷）</span></a></li></ol></li></ol></li></ol></section><!-- ov = overview--><section class="sidebar-ov hide"><div class="sidebar-ov-author"><div class="sidebar-ov-author__avatar"><img class="sidebar-ov-author__avatar_img" src="/blog/images/avatar.jpg" alt="avatar"></div><p class="sidebar-ov-author__text">C'est la vie</p></div><div class="sidebar-ov-state"><a class="sidebar-ov-state-item sidebar-ov-state-item--posts" href="/blog/archives/"><div class="sidebar-ov-state-item__count">48</div><div class="sidebar-ov-state-item__name">归档</div></a><a class="sidebar-ov-state-item sidebar-ov-state-item--categories" href="/blog/categories/"><div class="sidebar-ov-state-item__count">19</div><div class="sidebar-ov-state-item__name">分类</div></a><a class="sidebar-ov-state-item sidebar-ov-state-item--tags" href="/blog/tags/"><div class="sidebar-ov-state-item__count">20</div><div class="sidebar-ov-state-item__name">标签</div></a></div><div class="sidebar-ov-cc"><a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en" target="_blank" rel="noopener" data-popover="知识共享许可协议" data-popover-pos="up"><img src="/blog/images/cc-by-nc-sa.svg"></a></div></section><div class="sidebar-reading"><div class="sidebar-reading-info"><span class="sidebar-reading-info__text">你已阅读了 </span><span class="sidebar-reading-info__num">0</span><span class="sidebar-reading-info__perc">%</span></div><div class="sidebar-reading-line"></div></div></aside></div><div class="clearfix"></div></div></main><footer class="footer" id="footer"><div class="footer-inner"><div><span>Copyright © 2021</span><span class="footer__icon"><i class="fas fa-heart"></i></span><span>何水浪</span></div><div><span>由 <a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a> 强力驱动</span><span> v5.4.0</span><span class="footer__devider">|</span><span>主题 - <a href="https://github.com/liuyib/hexo-theme-stun/" title="Stun" target="_blank" rel="noopener">Stun</a></span><span> v2.6.2</span></div></div></footer><div class="loading-bar" id="loading-bar"><div class="loading-bar__progress"></div></div><div class="back2top" id="back2top"><span class="back2top__icon"><i class="fas fa-rocket"></i></span></div></div><div class="search-mask"></div><div class="search-popup"><span class="search-close"></span><div class="search-input"><input placeholder="搜索文章（支持多关键词，请用空格分隔）"></div><div class="search-results"></div></div><script src="https://cdn.jsdelivr.net/npm/jquery@v3.4.1/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.5.2/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.5.2/velocity.ui.min.js"></script><script>function initSearch() {
  var isXML = true;
  var search_path = 'search.json';

  if (!search_path) {
    search_path = 'search.xml';
  } else if (/json$/i.test(search_path)) {
    isXML = false;
  }

  var path = '/blog/' + search_path;
  $.ajax({
    url: path,
    dataType: isXML ? 'xml' : 'json',
    async: true,
    success: function (res) {
      var datas = isXML ? $('entry', res).map(function () {
        // 将 XML 转为 JSON
        return {
          title: $('title', this).text(),
          content: $('content', this).text(),
          url: $('url', this).text()
        };
      }).get() : res;
      var $input = $('.search-input input');
      var $result = $('.search-results');
      // 搜索对象（标题、内容）的权重，影响显示顺序
      var WEIGHT = { title: 100, content: 1 };
      var searchPost = function () {
        var searchText = $input.val().toLowerCase().trim();
        // 根据空白字符分隔关键字
        var keywords = searchText.split(/[\s]+/);
        // 搜索结果
        var matchPosts = [];

        // 有多个关键字时，将原文字整个保存下来
        if (keywords.length > 1) {
          keywords.push(searchText);
        }
        // 防止未输入字符时搜索
        if (searchText.length > 0) {
          datas.forEach(function (data) {
            var isMatch  = false;
            // 没有标题的文章使用预设的 i18n 变量代替
            var title = (data.title && data.title.trim()) || '[ 文章无标题 ]';
            var titleLower = title && title.toLowerCase();
            // 删除 HTML 标签 和 所有空白字符
            var content = data.content && data.content.replace(/<[^>]+>/g, '');
            var contentLower = content && content.toLowerCase();
            // 删除重复的 /
            var postURL = data.url && decodeURI(data.url).replace(/\/{2,}/g, '/');
            // 标题中匹配到的关键词
            var titleHitSlice = [];
            // 内容中匹配到的关键词
            var contentHitSlice = [];

            keywords.forEach(function (keyword) {
              /**
              * 获取匹配的关键词的索引
              * @param {String} keyword 要匹配的关键字
              * @param {String} text 原文字
              * @param {Boolean} caseSensitive 是否区分大小写
              * @param {Number} weight 匹配对象的权重。权重大的优先显示
              * @return {Array}
              */
              function getIndexByword (word, text, caseSensitive, weight) {
                if (!word || !text) {
                  return [];
                };

                var startIndex = 0; // 每次匹配的开始索引
                var index = -1;     // 匹配到的索引值
                var result = [];    // 匹配结果

                if (!caseSensitive) {
                  word = word.toLowerCase();
                  text = text.toLowerCase();
                }

                while((index = text.indexOf(word, startIndex)) !== -1) {
                  var hasMatch = false;
                  // 索引位置相同的关键词，保留长度较长的
                  titleHitSlice.forEach(function (hit) {
                    if (hit.index === index && hit.word.length < word.length) {
                      hit.word = word;
                      hasMatch = true;
                    }
                  });
                  startIndex = index + word.length;
                  !hasMatch && result.push({ index: index, word: word, weight: weight });
                }
                return result;
              }
              titleHitSlice = titleHitSlice.concat(getIndexByword(keyword, titleLower, false, WEIGHT.title));
              contentHitSlice = contentHitSlice.concat(getIndexByword(keyword, contentLower, false, WEIGHT.content));
            });

            var hitTitle = titleHitSlice.length;
            var hitContent = contentHitSlice.length;

            if (hitTitle > 0 || hitContent > 0) {
              isMatch = true;
            }
            if (isMatch) {
              ;[titleHitSlice, contentHitSlice].forEach(function (hit) {
                // 按照匹配文字的索引的递增顺序排序
                hit.sort(function (left, right) {
                  return left.index - right.index;
                });
              });
              /**
              * 给文本中匹配到的关键词添加标记，从而进行高亮显示
              * @param {String} text 原文本
              * @param {Array} hitSlice 匹配项的索引信息
              * @param {Number} start 开始索引
              * @param {Number} end 结束索引
              * @return {String}
              */
              function highlightKeyword (text, hitSlice, start, end) {
                if (!text || !hitSlice || !hitSlice.length) {
                  return;
                }

                var result = '';
                var startIndex = start;
                var endIndex = end;
                hitSlice.forEach(function (hit) {
                  if (hit.index < startIndex) {
                    return;
                  }

                  var hitWordEnd = hit.index + hit.word.length;
                  result += text.slice(startIndex, hit.index);
                  result += '<b>' + text.slice(hit.index, hitWordEnd) + '</b>';
                  startIndex = hitWordEnd;
                });
                result += text.slice(startIndex, endIndex);
                return result;
              }

              var postData = {};
              // 文章总的搜索权重
              var postWeight = titleHitSlice.length * WEIGHT.title + contentHitSlice.length * WEIGHT.content;
              // 标记匹配关键词后的标题
              var postTitle = highlightKeyword(title, titleHitSlice, 0, title.length) || title;
              // 标记匹配关键词后的内容
              var postContent;
              // 显示内容的长度
              var SHOW_WORD_LENGTH = 200;
              // 命中关键词前的字符显示长度
              var SHOW_WORD_FRONT_LENGTH = 20;
              var SHOW_WORD_END_LENGTH = SHOW_WORD_LENGTH - SHOW_WORD_FRONT_LENGTH;

              // 截取匹配的第一个字符，前后共 200 个字符来显示
              if (contentHitSlice.length > 0) {
                var firstIndex = contentHitSlice[0].index;
                var start = firstIndex > SHOW_WORD_FRONT_LENGTH ? firstIndex - SHOW_WORD_FRONT_LENGTH : 0;
                var end = firstIndex + SHOW_WORD_END_LENGTH;
                postContent = highlightKeyword(content, contentHitSlice, start, end);
              } else { // 未匹配到内容，直接截取前 200 个字符来显示
                postContent = content.slice(0, SHOW_WORD_LENGTH);
              }
              postData.title = postTitle;
              postData.content = postContent;
              postData.url = postURL;
              postData.weight = postWeight;
              matchPosts.push(postData);
            }
          });
        }

        var resultInnerHtml = '';
        if (matchPosts.length) {
          // 按权重递增的顺序排序，使权重大的优先显示
          matchPosts.sort(function (left, right) {
            return right.weight - left.weight;
          });
          resultInnerHtml += '<ul>';
          matchPosts.forEach(function (post) {
            resultInnerHtml += '<li><a class="search-results-title" href="' + post.url + '">';
            resultInnerHtml += post.title;
            resultInnerHtml += '</a><div class="search-results-content">';
            resultInnerHtml += post.content;
            resultInnerHtml += '</div></li>';
          });
          resultInnerHtml += '</ul>';
        } else {
          resultInnerHtml += '<div class="search-results-none"><i class="far fa-meh"></i></div>';
        }
        $result.html(resultInnerHtml);
      };
      $input.on('input', searchPost);
      $input.on('keyup', function (e) {
        if (e.keyCode === Stun.utils.codeToKeyCode('Enter')) {
          searchPost();
        }
      });
    }
  });
}

function closeSearch () {
  $('body').css({ overflow: 'auto' });
  $('.search-popup').css({ display: 'none' });
  $('.search-mask').css({ display: 'none' });
}

window.addEventListener('DOMContentLoaded', function () {
  Stun.utils.pjaxReloadLocalSearch = function () {
    $('.header-nav-search').on('click', function (e) {
      e.stopPropagation();
      $('body').css('overflow', 'hidden');
      $('.search-popup')
        .velocity('stop')
        .velocity('transition.expandIn', {
          duration: 300,
          complete: function () {
            $('.search-popup input').focus();
          }
        });
      $('.search-mask')
        .velocity('stop')
        .velocity('transition.fadeIn', {
          duration: 300
        });

      initSearch();
    });
    $('.search-mask, .search-close').on('click', function () {
      closeSearch();
    });
    $(document).on('keydown', function (e) {
      // Escape <=> 27
      if (e.keyCode === Stun.utils.codeToKeyCode('Escape')) {
        closeSearch();
      }
    });
  };

  Stun.utils.pjaxReloadLocalSearch();
}, false);

function safeOpenUrl(url) {
  var newTab = window.open();
  newTab.opener = null;
  newTab.location = url;
}

function extSearch(engine) {
  var engines = {
    google: 'https://www.google.com/search?q=',
    bing: 'https://cn.bing.com/search?q=',
    baidu: 'https://www.baidu.com/s?ie=UTF-8&wd=',
  };
  var host = window.location.host;
  var query = $('.search-input input').val().toLowerCase().trim();
  var uri = engines[engine] + query + ' site:' + host;

  if (query) {
    safeOpenUrl(uri);
  } else {
    Stun.utils.popAlert('warning', '请输入字符');
  }
}

var assistSearchList = window.CONFIG.assistSearch;

if (Array.isArray(assistSearchList)) {
  assistSearchList.forEach(function (name) {
    document.querySelector('.search-btns-item--' + name).addEventListener('click', function () {
      extSearch(name);
    }, false);
  });
}</script><script src="https://cdn.jsdelivr.net/npm/leancloud-storage@latest/dist/av-min.js"></script><script src="https://cdn.jsdelivr.net/npm/valine@latest/dist/Valine.min.js"></script><script>function loadValine () {
  var GUEST_INFO = ['nick', 'mail', 'link'];
  var guest_info = 'nick';

  guest_info = guest_info.split(',').filter(function(item) {
    return GUEST_INFO.indexOf(item) > -1;
  });
  new Valine({
    el: '#valine-container',
    appId: 'fJ4fFnieffDVKy4Jkn16aHdO-gzGzoHsz',
    appKey: 'qfVo2CUC2pJ3udFzLFnd0GBM',
    notify: true,
    verify: true,
    placeholder: '说点啥再走呗~爱你',
    avatar: 'mp',
    meta: guest_info,
    pageSize: '10' || 10,
    visitor: false,
    recordIP: false,
    lang: '' || 'zh-cn',
    path: window.location.pathname
  });
}

if (false) {
  loadValine();
} else {
  window.addEventListener('DOMContentLoaded', loadValine, false);
}</script><script src="/blog/js/utils.js?v=2.6.2"></script><script src="/blog/js/stun-boot.js?v=2.6.2"></script><script src="/blog/js/scroll.js?v=2.6.2"></script><script src="/blog/js/header.js?v=2.6.2"></script><script src="/blog/js/sidebar.js?v=2.6.2"></script><script type="application/json" src="/blog/search.json"></script></body></html>